package com.app.piemoment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.TransitOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKGeocoderAddressComponent;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class LocationActivity extends BaseActivity {
	private int lat = (int)(39.9411 * 1E6),lon = (int)(116.3714 * 1E6);
	private int lat1 = (int)(39.9498 * 1E6),lon1 = (int)(116.3785 * 1E6);
	
	static MapView mMapView;
	public MKMapViewListener mMapListener = null;
	OverlayTest ov = null;
	// 存放overlayitem 
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	// 存放overlay图片
	private MKSearch mSearch;
	private PieMomentApp app;
	private String strNode,endNode;

	public LocationActivity() {
		mainViewId = R.layout.location_activity;
	}

	@Override
	protected void initMainView() {
		initTitle(R.drawable.btn_back_bg, "距离", 0,0);
		mMapView = (MapView)findViewById(R.id.bmapView);
		app = (PieMomentApp)this.getApplication();
	}

	@Override
	protected void registerMainViewEvent() {
		
		/*mSearch = new MKSearch();
		mSearch.init(app.mBMapManager, new MKSearchListener() {
			@Override
			public void onGetPoiDetailSearchResult(int type, int error) {
			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
				if (error != 0) {
					String str = String.format("错误号：%d", error);
					Toast.makeText(LocationActivity.this, str, Toast.LENGTH_LONG).show();
					return;
				}
				GeoPoint geoPt = res.geoPt;
				
				Log.e("位置1", geoPt.getLatitudeE6()/1000 +"  "+ geoPt.getLongitudeE6()/1000);
				Log.e("位置1", lat/1000 +"  "+ lon/1000);
				Log.e("位置1", lat1/1000 +"  "+ lon1/1000);
				
				if(isSame(lat, lon, geoPt)) {
					MKGeocoderAddressComponent component = res.addressComponents;
					if(component!=null) {
						Log.e("位置1", component.city + component.district + component.street + component.streetNumber);
						strNode = component.district;
					}
				}else if(isSame(lat1, lon1, geoPt)) {
					MKGeocoderAddressComponent component = res.addressComponents;
					if(component!=null) {
						Log.e("位置2", component.city + component.district + component.street + component.streetNumber);
						endNode = component.district;
					}
				}
				//TODO 获取地址信息

				if(strNode!=null&&endNode!=null) {
					MKPlanNode stNode = new MKPlanNode();
					stNode.name = null;
					MKPlanNode enNode = new MKPlanNode();
					enNode.name = null;
					mSearch.transitSearch("北京", stNode, enNode);
				}

			}
			public void onGetPoiResult(MKPoiResult res, int type, int error) {
			}
			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
			}
			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(LocationActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
					return;
				}
				TransitOverlay  routeOverlay = new TransitOverlay (LocationActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.refresh();
				// 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(), routeOverlay.getLonSpanE6());
				mMapView.getController().animateTo(res.getStart().pt);
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) {
			}
			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}
			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			}

		});
		GeoPoint ptCenter = new GeoPoint(lat, lon);
		mSearch.reverseGeocode(ptCenter);
		
		ptCenter = new GeoPoint(lat1, lon1);
		mSearch.reverseGeocode(ptCenter);


		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {

			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(LocationActivity.this,title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
			}

			@Override
			public void onMapAnimationFinish() {

			}
		};*/
	}
	
	/*private boolean isSame(int lat, int lon, GeoPoint geoPt) {
		if(lat/1000==geoPt.getLatitudeE6()/1000&&lon/1000==geoPt.getLongitudeE6()/1000) {
			return true;
		}
		return false;
	}
*/

	@Override
	protected void processMainView() {
	
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PieMomentApp.strKey,new PieMomentApp.MyGeneralListener());
        }
       
        mMapView = (MapView)findViewById(R.id.bmapView);
        initMapView();
        mMapView.getController().setZoom(12);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);
        
        Drawable marker = LocationActivity.this.getResources().getDrawable(R.drawable.icon_marka);
	    mMapView.getOverlays().clear();
	    ov = new OverlayTest(marker, this,mMapView); 
	    mMapView.getOverlays().add(ov);
     
		mMapView.regMapViewListener(PieMomentApp.getInstance().mBMapManager, mMapListener);
		
		
		// 准备overlay 数据
		OverlayItem item= new OverlayItem(new GeoPoint(lat,lon),"A","A");
	   	item.setMarker(getResources().getDrawable(R.drawable.icon_marka));
	   	mGeoList.add(item);
	   	
	   	item= new OverlayItem(new GeoPoint(lat1,lon1),"B","B");
	   	item.setMarker(getResources().getDrawable(R.drawable.icon_markb));
	   	mGeoList.add(item);
	   	testItemClick();
	}
	
	 @Override
	    protected void onPause() {
	        mMapView.onPause();
	        super.onPause();
	    }
	    
	    @Override
	    protected void onResume() {
	        mMapView.onResume();
	        super.onResume();
	    }
	    
	    @Override
	    protected void onSaveInstanceState(Bundle outState) {
	    	super.onSaveInstanceState(outState);
	    	mMapView.onSaveInstanceState(outState);
	    	
	    }
	    
	    @Override
	    protected void onRestoreInstanceState(Bundle savedInstanceState) {
	    	super.onRestoreInstanceState(savedInstanceState);
	    	mMapView.onRestoreInstanceState(savedInstanceState);
	    }
	    
	    @Override
	    protected void onDestroy() {
	        mMapView.destroy();
	        super.onDestroy();
	    }
	    
	    private void initMapView() {
	        mMapView.setLongClickable(true);
	        //mMapController.setMapClickEnable(true);
	        //mMapView.setSatellite(false);
	    }
	  
	    /**
	     * 添加标注
	     */
	    public void testItemClick() {
	    	//添加一个item
	    	//当要添加的item较多时，可以使用addItem(List<OverlayItem> items) 接口
	    	if ( ov.size() < mGeoList.size()){
//	    		ov.addItem(mGeoList.get(ov.size() ));
	    		ov.addItem(mGeoList);
	    	}
	    	mMapView.refresh();
	   }
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			super.onBackPressed();
			break;

		default:
			break;
		}
	}
}
class OverlayTest extends ItemizedOverlay<OverlayItem> {
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Context mContext = null;
	static PopupOverlay pop = null;
	
	Toast mToast = null;
	
	public OverlayTest(Drawable marker,Context context, MapView mapView){
		super(marker,mapView);
		this.mContext = context;
		pop = new PopupOverlay(LocationActivity.mMapView,new PopupClickListener() {
			
			@Override
			public void onClickedPopup(int index) {
				/*if (null == mToast)
					mToast = Toast.makeText(mContext, "popup item :" + index + " is clicked.", Toast.LENGTH_SHORT);
				else mToast.setText("popup item :" + index + " is clicked.");
				mToast.show();*/
			}
		});
		// 自2.1.1 开始，使用 add/remove 管理overlay , 无需调用以下接口.
		// populate();
		
	}
	protected boolean onTap(int index) {
		System.out.println("item onTap: "+index);
		
		Bitmap[] bmps = new Bitmap[3];
		if(0==index) {
			bmps[0] = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_opp_icon);
		}else {
			bmps[0] = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_personal_icon);
		}
		pop.showPopup(bmps, getItem(index).getPoint(), 32);
		if (null == mToast)
			mToast = Toast.makeText(mContext, getItem(index).getTitle(), Toast.LENGTH_SHORT);
		else mToast.setText(getItem(index).getTitle());
		mToast.show();
		
		
		return true;
	}
	public boolean onTap(GeoPoint pt, MapView mapView){
		if (pop != null){
			pop.hidePop();
		}
		super.onTap(pt,mapView);
		return false;
	}
}
